﻿#include "binaryrainwidget1.h"
#include <QPainter>
#include <QRandomGenerator>
#include <QtMath>
#include <QString>

BinaryRainWidget::BinaryRainWidget(QWidget *parent)
    : QWidget(parent), timer(new QTimer(this))
{
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(windowFlags() | Qt::FramelessWindowHint);

    connect(timer, &QTimer::timeout, this, &BinaryRainWidget::updateRain);
    timer->start(5); // 50 ms interval for smoother animation

    initializeColumns();
}

BinaryRainWidget::~BinaryRainWidget()
{
    delete timer;
}

void BinaryRainWidget::initializeColumns()
{
    columns.clear();
    int columnCount = width() / 15; // Adjust based on desired density

    for (int i = 0; i < columnCount; ++i) {
        RainColumn col;
        col.chars = QVector<QChar>(QRandomGenerator::global()->bounded(10, 20));
        col.yPositions = QVector<int>(col.chars.size());
        col.colors = QVector<QColor>(col.chars.size(), QColor(0, 255, 0));
        col.speed = QRandomGenerator::global()->bounded(1, 3);
        col.isActive = false;

        for (int j = 0; j < col.chars.size(); ++j) {
            col.chars[j] = QChar('0' + QRandomGenerator::global()->bounded(2));
            col.yPositions[j] = -j * 20; // Initial position above the screen
        }

        columns.append(col);
    }
}

void BinaryRainWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    for (int k = 0; k < columns.size(); ++k) {
        RainColumn col = columns.at(k);
        if (!col.isActive)
            continue;
        int x = width() / columns.size() * k; // 假设每列都有一个固定的X坐标
        for (int i = 0; i < col.chars.size(); ++i) {
            painter.setPen(col.colors[i]);
            painter.drawText(x, col.yPositions[i], QString(col.chars[i]));
        }
    }
}

void BinaryRainWidget::resizeEvent(QResizeEvent *)
{
    initializeColumns();
}

void BinaryRainWidget::updateRain()
{
    for (auto &col : columns) {
        if (QRandomGenerator::global()->bounded(100) < 5) { // Random activation chance
            col.isActive = true;
        }

        if (col.isActive) {
            for (int i = 0; i < col.chars.size(); ++i) {
                col.yPositions[i] += col.speed;
                if (col.yPositions[i] > height()) {
                    col.yPositions[i] = -i * 20; // Reset to top
                }
            }
        } else {
            // Optionally reset positions when not active
            for (int i = 0; i < col.chars.size(); ++i) {
                col.yPositions[i] = -i * 20;
            }
        }
    }

    update(); // Trigger repaint
}
